package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        // 解决缓存穿透
//        Shop shop = queryByPassThrough(id);
//        Shop shop = cacheClient.queyWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS);

        // 互斥锁解决缓存击穿
        Shop shop = queryByMutex(id);

        // 逻辑延时解决缓存击穿
//        Shop shop = queryByLogicalExpire(id);
//        Shop shop = cacheClient.queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY,
//                id, Shop.class, this::getById, 10L, TimeUnit.SECONDS, RedisConstants.LOCK_SHOP_KEY);

        if(shop==null){
            return Result.fail("店铺不存在");
        }

        return Result.ok(shop);
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1. 判断坐标参数是否为空, 如果为空, 则按照默认顺序查询
        if (x==null||y==null) {
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        //2. 分页参数计算
        int from = SystemConstants.DEFAULT_PAGE_SIZE * (current - 1);
        int end = SystemConstants.DEFAULT_PAGE_SIZE * current;

        //3. 计算最近的店铺, 包含参数: 分页, 当前坐标, 类型
        String key=RedisConstants.SHOP_GEO_KEY+typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = stringRedisTemplate.opsForGeo().search(key,
                GeoReference.fromCoordinate(new Point(x, y)),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        if (geoResults==null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = geoResults.getContent();
        if(content.size()<=from){
            return Result.ok(Collections.emptyList());
        }

        //4. 计算要查的店铺id集合
        List<Long> shopIdList=new ArrayList<>(content.size());
        Map<String,Double> shopId2DistanceMap=new HashMap<>();
        content.stream().skip(from).forEach(item->{
            String shopIdStr = item.getContent().getName();
            shopIdList.add(Long.parseLong(shopIdStr));

            double distance = item.getDistance().getValue();
            shopId2DistanceMap.put(shopIdStr,distance);
        });

        //5. 查询店铺
        String shopIdStr = StrUtil.join(",", shopIdList);
        List<Shop> shopList = query().in("id", shopIdList).last("order by FIELD(id," + shopIdStr + ")").list();

        //5.1. 填充距离信息
        for (Shop shop : shopList) {
            shop.setDistance(shopId2DistanceMap.get(shop.getId().toString()));
        }

        //6. 返回
        return Result.ok(shopList);


    }

    private final static ExecutorService EXECUTOR_SERVICE=Executors.newFixedThreadPool(10);

    // 仅适用于已经放入缓存的热点数据
    public Shop queryByLogicalExpire(Long id){
        //1. 从redis中查询商铺
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        //2. 判断缓存是否命中
        if (StrUtil.isBlank(shopJson)) {
            //3. 命中则直接返回
            return null;
        }

        //3. 反序列化获取对象和过期时间
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = BeanUtil.toBean((JSONObject) redisData.getData(), Shop.class);



        //4. 判断缓存是否过期
        if(LocalDateTime.now().isAfter(redisData.getExpireTime())){
            //尝试获取互斥锁
            String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
            boolean b = tryLock(lockKey);

            if(b){
                //5. 如果过期, 则开启独立线程, 将现有数据存到redis中
                EXECUTOR_SERVICE.execute(()->{
                    try {
                        saveShop2Redis(id,10L);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        unlock(lockKey);
                    }
                });
            }

        }

        //5. 无论是否过期, 都将当前数据返回
        return shop;
    }

    public Shop queryByMutex(Long id){
        //1. 从redis中查询商铺
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        //2. 判断缓存是否命中
        if (StrUtil.isNotBlank(shopJson)) {
            //3. 命中则直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        if(shopJson!=null){
            return null;
        }

        //3. 尝试加锁并判断

        String lockShop="lock:shop:"+id;
        Shop shop;
        try {
            boolean lock = tryLock(lockShop);
            if(!lock){
                //3.1. 如果加锁失败, 则等待
                Thread.sleep(50);
                return queryByMutex(id);
            }

            //3.2 如果加锁成功, 则继续从数据库查询

            //4. 未命中,则根据id查询数据库
            shop = getById(id);
            // 模拟查询数据很慢
            Thread.sleep(3000);

            //5. 数据库不存在,返回404
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            //6. 数据库存在,则将商铺写入redis中
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            unlock(lockShop);
        }

        //7.返回商铺

        return shop;
    }

    public Shop queryByPassThrough(Long id){
        //1. 从redis中查询商铺
        String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        //2. 判断缓存是否命中
        if (StrUtil.isNotBlank(shopJson)) {
            //3. 命中则直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        if(shopJson!=null){
            return null;
        }

        //4. 未命中,则根据id查询数据库
        Shop shop = getById(id);

        //5. 数据库不存在,返回404
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        //6. 数据库存在,则将商铺写入redis中
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //7.返回商铺
        return shop;
    }

    public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
        Shop shop = getById(id);
        // 模拟延时
        Thread.sleep(200);

        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));

        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    private boolean tryLock(String key){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    @Override
    public Result update(Shop shop) {
        if (shop.getId()==null) {
            return Result.fail("店铺id不能为空");
        }

        updateById(shop);

        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY+shop.getId());

        return Result.ok();
    }
}
